﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;
using System.Reflection;
using System.Data.Entity;
using System.Net;
using System.Security.Cryptography;
using System.Net.Mail;


namespace ArbabTravelsERP.DAL
{
    public class DataUtility
    {
        private DataTable dt;
        private DataSet ds;
        private DbSet dbset;

        private static string StrCon = (ConfigurationManager.ConnectionStrings["ARBAB_Entities"].ConnectionString.ToString());
       
        private string LOG_FILE = "C:\\Errorlogs\\ErrorLogs.txt" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString();

        public void TraceService(string content)
        {
            //set up a filestream
            FileStream fs = new FileStream(LOG_FILE, FileMode.OpenOrCreate, FileAccess.Write);

            //set up a streamwriter for adding text
            StreamWriter sw = new StreamWriter(fs);

            //find the end of the underlying filestream
            sw.BaseStream.Seek(0, SeekOrigin.End);

            //add the text
            sw.WriteLine(content);
            //add the text to the underlying filestream

            sw.Flush();
            //close the writersw.Close();

            sw.Close();
        }

        public SqlConnection con()
        {
            SqlConnection con = new SqlConnection(StrCon);
            if (con.State == ConnectionState.Closed) con.Open();
            return con;
        }

        //If connection is open then To close connection
        private SqlConnection conClose(SqlConnection con)
        {
            if (con != null && con.State == ConnectionState.Open)
                con.Close();

            return con;
        }

        public static List<TSource> ToList<TSource>() where TSource : new()
        {

            DataTable dataTable = new DataTable();
            var dataList = new List<TSource>();

            const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
            var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
                                 select new
                                 {
                                     Name = aProp.Name,
                                     Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType
                                 }).ToList();
            var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
                                     select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList();
            var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList();

            foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
            {
                var aTSource = new TSource();
                foreach (var aField in commonFields)
                {
                    PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
                    propertyInfos.SetValue(aTSource, dataRow[aField.Name], null);
                }
                dataList.Add(aTSource);
            }
            return dataList;
        }

        public DataTable ExecuteDataTable(string commandtype, string commandText, params SqlParameter[] commandParameters)
        {
            dt = new DataTable();
            try
            {
                using (SqlConnection CON = con())
                {
                    using (SqlDataAdapter dap = new SqlDataAdapter(commandText, CON))
                    {
                        dap.SelectCommand.CommandTimeout = 0;
                        if (commandtype == "StoredProcedure")
                            dap.SelectCommand.CommandType = CommandType.StoredProcedure;
                        else if (commandtype == "TableDirect")
                            dap.SelectCommand.CommandType = CommandType.TableDirect;
                        else
                            dap.SelectCommand.CommandType = CommandType.Text;

                        dap.SelectCommand.CommandTimeout = 0;
                        foreach (SqlParameter param in commandParameters)
                        {
                            dap.SelectCommand.Parameters.AddWithValue(param.ParameterName, param.Value);
                        }
                        dap.SelectCommand.CommandTimeout = 0;
                        dap.Fill(dt);

                        conClose(CON);
                        return dt;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally { dt = null; }
        }

        public DataSet ExecuteDataSet(string commandtype, string commandText, params SqlParameter[] commandParameters)
        {
            ds = new DataSet();
            using (SqlConnection CON = con())
            {
                using (SqlDataAdapter dap = new SqlDataAdapter(commandText, CON))
                {
                    dap.SelectCommand.CommandTimeout = 0;
                    if (commandtype == "StoredProcedure")
                        dap.SelectCommand.CommandType = CommandType.StoredProcedure;
                    else if (commandtype == "TableDirect")
                        dap.SelectCommand.CommandType = CommandType.TableDirect;
                    else
                        dap.SelectCommand.CommandType = CommandType.Text;

                    foreach (SqlParameter param in commandParameters)
                    {
                        dap.SelectCommand.Parameters.AddWithValue(param.ParameterName, param.Value);
                    }

                    dap.Fill(ds);

                    conClose(CON);
                    return ds;
                }
            }
        }

        public DataSet ExecuteDataSet(string commandtype, string commandText)
        {
            ds = new DataSet();
            using (SqlConnection CON = con())
            {
                using (SqlDataAdapter dap = new SqlDataAdapter(commandText, CON))
                {
                    dap.SelectCommand.CommandTimeout = 0;
                    if (commandtype == "StoredProcedure")
                        dap.SelectCommand.CommandType = CommandType.StoredProcedure;
                    else if (commandtype == "TableDirect")
                        dap.SelectCommand.CommandType = CommandType.TableDirect;
                    else
                        dap.SelectCommand.CommandType = CommandType.Text;

                    dap.Fill(ds);
                    return ds;
                }
            }
        }

        public string ExecuteScalardb(string commandtype, string commandText, params SqlParameter[] commandParameters)
        {
            ds = new DataSet();
            using (SqlConnection CON = con())
            {
                using (SqlCommand cmd = new SqlCommand(commandText, CON))
                {
                    cmd.CommandTimeout = 0;
                    if (commandtype == "StoredProcedure")
                        cmd.CommandType = CommandType.StoredProcedure;
                    else if (commandtype == "TableDirect")
                        cmd.CommandType = CommandType.TableDirect;
                    else
                        cmd.CommandType = CommandType.Text;

                    foreach (SqlParameter param in commandParameters)
                    {
                        cmd.Parameters.AddWithValue(param.ParameterName, param.Value);
                    }

                    //Return string bcs if any error is coming then it will return text message and directly go in to throw expression.
                    string result = cmd.ExecuteNonQuery().ToString();

                    conClose(CON);
                    return result;
                }
            }
        }

        public int ExceuteNonQuery(string commandtype, string commandText, params SqlParameter[] commandParameters)
        {
            ds = new DataSet();
            using (SqlConnection CON = con())
            {
                using (SqlCommand cmd = new SqlCommand(commandText, CON))
                {
                    cmd.CommandTimeout = 0;
                    if (commandtype == "StoredProcedure")
                        cmd.CommandType = CommandType.StoredProcedure;
                    else if (commandtype == "TableDirect")
                        cmd.CommandType = CommandType.TableDirect;
                    else
                        cmd.CommandType = CommandType.Text;

                    foreach (SqlParameter param in commandParameters)
                    {
                        cmd.Parameters.AddWithValue(param.ParameterName, param.Value);
                    }

                    //Return string bcs if any error is coming then it will return text message and directly go in to throw expression.
                    return cmd.ExecuteNonQuery();
                }
            }
        }


        //public void LogError(string PageName, string PageUrl, string MethodName, string ErrorMessage, string InnerException, string userIP, string userCode)
        //{
        //    string Host_IP = GetIP4Address();
        //    using (LMSDataClassesDataContext dbcontext = new LMSDataClassesDataContext())
        //    {
        //        TBL_ERROR_LOG error = new TBL_ERROR_LOG();
        //        error.PAGE_NAME = PageName;
        //        error.PAGE_URL = PageUrl;
        //        error.METHOD_NAME = MethodName;
        //        error.ERROR_MESSAGE = ErrorMessage;
        //        error.INNER_EXCEPTION_MESSAGE = InnerException;
        //        error.USER_IP = Host_IP;
        //        error.USER_CODE = userCode;
        //        error.CREATED_DATE = DateTime.Now;
        //        dbcontext.TBL_ERROR_LOGs.InsertOnSubmit(error);
        //        dbcontext.SubmitChanges();

        //    }
        //}

        public DbSet db()
        {


            return dbset;
        }

    }
}

